import {
  pieTemplateFactory,
  barTemplateFactory,
  lineTemplateFactory,
  areaTemplateFactory,
  _ts,
  radarTemplateFactory
} from './utils';
import { deepCopy, messages } from 'share/common';

function toPercentage(num) {
  return ((num || 0) * 100).toFixed(2) + '%';
}

/**
 * 这个文件用来生成echarts的options
 */

/**
 * 通用饼图
 * @param data
 * @param verticalLegend
 * @param subtext 副标题
 * @returns {{tooltip, legend, series}}
 */
export function commonPieReportFactory(data, verticalLegend, labelValue, subtext, widget) {
  let template = pieTemplateFactory(verticalLegend);
  let legendData = [],
    seriesData = [];
  let total = 0;
  let dimensionName = labelValue.dimension.name;
  let dimensionCode = labelValue.dimension.code;

  let linkageColumnPropName = widget.reportChartDetails && widget.reportChartDetails.filter(item => item.fieldType === 'dimension').length !== 0 && widget.reportChartDetails.filter(item => item.fieldType === 'dimension')[0].linkageColumnPropName;

  let indicator = labelValue.indicator[0] || {};

  data.forEach(item => {
    let value = item[indicator.code],
      label = item[dimensionCode];
    item._valueNum = (Number(value) || 0);
    total += item._valueNum;
    legendData.push(label);
    seriesData.push({
      value,
      name: label,
      label: indicator.name,
      data: item
    });
  });
  seriesData.forEach(item => {
    item[linkageColumnPropName] = item.data[linkageColumnPropName];
    item._percentageStr = toPercentage((Number(item.value) || 0) / total);
  });
  if (subtext) {
    template.title = {
      text: total,
      textAlign: 'center',
      subtext,
      bottom: 'center',
      left: '59%'
    };
  }

  let formatter = '';

  if (widget.showDimensionFlag) {
    formatter += '{b}';
  }
  if (widget.showIndicatorFlag) {
    formatter += ' {c}';
  }
  if (widget.showPercentFlag) {
    formatter += ' ({d}%)';
  }

  template.legend.data = legendData;
  template.series[0].data = seriesData;

  if (formatter === '') {
    template.series[0].labelLine.show = false;
  }
  template.series[0].label.normal.formatter = formatter;

  if (widget.showLegendLocation === 'false') {
    template.legend.show = false;
    template.series[0].center = ['50%', '50%'];
  } else if (widget.showLegendLocation === 'left') {
    delete template.legend.right;
    template.legend.left = 10;
    template.series[0].center = ['60%', '50%'];
  } else if (widget.showLegendLocation === 'up') {
    delete template.legend.right;
    template.legend.top = 10;
    template.series[0].center = ['50%', '60%'];
  } else if (widget.showLegendLocation === 'down') {
    delete template.legend.right;
    template.legend.bottom = 10;
    template.series[0].center = ['50%', '40%'];
  }

  return template;
}

/**
 * 通用柱状图
 * @param data
 * @param colorIndex
 * @returns {{tooltip, legend, series}}
 *
 */
export function commonBarReportFactory(data, labelValue, isHorizon, widget) {
  let template = barTemplateFactory(isHorizon, widget.narrowRangeFlag);

  const seriesTemplate = barTemplateFactory().series[0];

  let yAxisData = [];
  let dimensionName = labelValue.dimension.name;
  let dimensionCode = labelValue.dimension.code;

  let indicator = labelValue.indicator;
  let indicatorLength = (indicator && indicator.length) || 1;

  // let valueName = labelValue.value[0];

  indicator.forEach((single, index) => {

    let seriesData = [];

    data.forEach((item) => {
      let data = deepCopy(item);
      data._valueNum = (Number(item[single.code]) || 0);
      data.value = (Number(item[single.code]) || 0);
      data.label = single.name;
      data.data = item;
      data.valueBelongName = item[dimensionCode];
      index === 0 && yAxisData.push(item[dimensionCode]);
      seriesData.push(data);
    });

    template.series[index] = deepCopy(seriesTemplate);

    template.series[index].data = seriesData;
    template.series[index].barWidth = `${80 / indicatorLength}%`;

    if (!widget.showLabelFlag) {
      template.series[index].label.normal.show = false;
    }

    if (!isHorizon) {
      template.series[index].label.normal.position = 'top';
    }

  });

  template.yAxis[0].data = yAxisData;
  /*
  * 提示框不截取字符串，由于字符串太长，不仅需要把字符串格式化，
  * 还需要对字符串显示的位置进行处理，不然显示在图标区外面，也会看不见
  * */

  /**
   * 所有label在hover时都展示全部，为避免过长被遮挡，全部重写position
   *
   * 提示框不截取字符串，由于字符串太长，不仅需要把字符串格式化，
   * 还需要对字符串显示的位置进行处理，不然显示在图标区外面，也会看不见
   * @param point
   * @param params
   * @param dom
   * @param rect
   * @param size
   */
  template.tooltip.position = function (point, params, dom, rect, size) {
    // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
    // 提示框位置
    let x = 0,
      y = 0; // x坐标位置,y坐标位置
    // 当前鼠标位置
    let pointX = point[0],
      pointY = point[1];
    // 外层div大小
    // var viewWidth = size.viewSize[0];
    // var viewHeight = size.viewSize[1];
    // 提示框大小
    let boxWidth = size.contentSize[0],
      boxHeight = size.contentSize[1];
    // boxWidth > pointX 说明鼠标左边放不下提示框
    if (boxWidth > pointX) {
      x = 5;
    } else { // 左边放的下
      x = pointX - boxWidth;
    }
    // boxHeight > pointY 说明鼠标上边放不下提示框
    if (boxHeight > pointY) {
      y = 5;
    } else { // 上边放得下
      y = pointY - boxHeight;
    }
    return [x, y];
  };


  if (isHorizon) {
    return template;
  } else {
    let temp = deepCopy(template.yAxis);
    template.yAxis = template.xAxis;
    template.xAxis = temp;
    template.xAxis[0].inverse = false;
    return template;
  }

}

/**
 * 通用折线图（横向）
 * @param data
 * @param colorIndex
 * @returns {{tooltip, legend, series}}
 *
 */
export function commonLineReportFactory(data, labelValue, widget) {


  let template = lineTemplateFactory(widget.narrowRangeFlag, ['left', 'right'].indexOf(widget.showLegendLocation) !== -1);

  const seriesTemplate = lineTemplateFactory().series[0];

  let xAxisData = [];
  let legendData = [];
  let dimensionName = labelValue.dimension.name;
  let dimensionCode = labelValue.dimension.code;

  let indicator = labelValue.indicator;


  indicator.forEach((single, index) => {

    let seriesData = [];

    data.forEach((item) => {
      let data = deepCopy(item);
      data.value = (Number(item[single.code]) || 0);
      data.name = single.name;
      index === 0 && xAxisData.push(item[dimensionCode]);
      data.data = item;
      seriesData.push(data);
    });

    legendData.push(single.name);

    template.series[index] = deepCopy(seriesTemplate);

    template.series[index].data = seriesData;
    template.series[index].name = single.name;

    if (!widget.showLabelFlag) {
      template.series[index].label.show = false;
    }

  });

  template.legend.data = legendData;

  if (widget.showLegendLocation === 'false') {
    template.legend.show = false;
  } else if (widget.showLegendLocation === 'left') {
    template.legend.left = 10;
    template.grid.top = '5%';
    template.grid.left = '150';
  } else if (widget.showLegendLocation === 'right') {
    template.legend.right = 10;
    template.grid.top = '5%';
    if (widget.narrowRangeFlag) {
      template.grid.right = '120';
    } else {
      template.grid.right = '150';
    }
  } else if (widget.showLegendLocation === 'down') {
    template.legend.bottom = 5;
    template.grid.top = '5%';
    if (widget.narrowRangeFlag) {
      template.grid.bottom = '70';
      template.dataZoom[0].bottom = '32';
    } else {
      template.grid.bottom = '10%';
    }
  } else if (widget.showLegendLocation === 'up') {
    delete template.legend.bottom;
    template.legend.top = 5;
  }

  template.xAxis.data = xAxisData;


  return template;
}

/**
 * 通用面积图（横向）
 * @param data
 * @param colorIndex
 * @returns {{tooltip, legend, series}}
 *
 */
export function commonAreaReportFactory(data, labelValue, widget) {


  let template = areaTemplateFactory(widget.narrowRangeFlag, ['left', 'right'].indexOf(widget.showLegendLocation) !== -1);

  const seriesTemplate = areaTemplateFactory().series[0];

  let xAxisData = [];
  let legendData = [];
  let dimensionName = labelValue.dimension.name;
  let dimensionCode = labelValue.dimension.code;

  let indicator = labelValue.indicator;


  indicator.forEach((single, index) => {

    let seriesData = [];

    data.forEach((item) => {
      let data = deepCopy(item);
      data.value = (Number(item[single.code]) || 0);
      data.name = single.name;
      index === 0 && xAxisData.push(item[dimensionCode]);
      data.data = item;
      seriesData.push(data);
    });

    legendData.push(single.name);

    template.series[index] = deepCopy(seriesTemplate);

    template.series[index].data = seriesData;
    template.series[index].name = single.name;

    template.series[index].areaStyle.color.colorStops[0].color = template.series[index].areaStyle.color.colorList[index % 5].start;
    template.series[index].areaStyle.color.colorStops[1].color = template.series[index].areaStyle.color.colorList[index % 5].end;

    if (!widget.showLabelFlag) {
      template.series[index].label.show = false;
    }

  });
  template.legend.data = legendData;

  if (widget.showLegendLocation === 'false') {
    template.legend.show = false;
  } else if (widget.showLegendLocation === 'left') {
    template.legend.left = 10;
    template.grid.top = '5%';
    template.grid.left = '150';
  } else if (widget.showLegendLocation === 'right') {
    template.legend.right = 10;
    template.grid.top = '5%';
    if (widget.narrowRangeFlag) {
      template.grid.right = '120';
    } else {
      template.grid.right = '150';
    }
  } else if (widget.showLegendLocation === 'down') {
    template.legend.bottom = 5;
    template.grid.top = '5%';
    if (widget.narrowRangeFlag) {
      template.grid.bottom = '70';
      template.dataZoom[0].bottom = '32';
    } else {
      template.grid.bottom = '10%';
    }
  } else if (widget.showLegendLocation === 'up') {
    delete template.legend.bottom;
    template.legend.top = 5;
  }

  template.xAxis.data = xAxisData;


  return template;
}

/**
 * 通用雷达图（横向）
 * @param data
 * @returns {{tooltip, legend, series}}
 *
 */
export function commonRadarReportFactory(data, labelValue, widget) {
  let template = radarTemplateFactory(['left', 'right'].indexOf(widget.showLegendLocation) !== -1);
  let areaStyleTem = deepCopy(radarTemplateFactory().series[0].areaStyle);
  let legend = { data: [] };
  let dimensionName = labelValue.dimension.name;
  let dimensionCode = labelValue.dimension.code;
  let indicator = labelValue.indicator;
  let indicatorArray = [];
  let dataArray = [];
  let maxArray = [];

  indicator.forEach((single, index) => {

    let valueArray = [];
    let singleIndicator = {
      name: single.name,
      areaStyle: deepCopy(areaStyleTem)
    };

    data.forEach((item) => {
      valueArray.push((Number(item[single.code]) || 0));
      index === 0 && indicatorArray.push({ name: item[dimensionCode] });
    });

    singleIndicator.value = valueArray;
    maxArray.push(Math.max(...valueArray));
    singleIndicator.areaStyle.color.colorStops[0].color = singleIndicator.areaStyle.color.colorList[index % 5].start;
    singleIndicator.areaStyle.color.colorStops[1].color = singleIndicator.areaStyle.color.colorList[index % 5].end;

    dataArray.push(singleIndicator);

    legend.data.push(single.name);

  });



  template.series[0].data = dataArray;
  template.series[0].name = dimensionName;

  if (!widget.showLabelFlag) {
    template.series[0].label.show = false;
  }

  template.radar.indicator = indicatorArray.map((item)=>{
    return {
      name: item.name,
      max: Math.max(...maxArray)
    }
  });
  template.legend.data = legend.data;

  if (widget.showLegendLocation === 'false') {
    template.legend.show = false;
    template.radar.center = ['50%', '50%']
  } else if (widget.showLegendLocation === 'left') {
    delete template.legend.right;
    template.legend.left = 10;
    template.radar.center = ['60%', '50%']
  } else if (widget.showLegendLocation === 'up') {
    delete template.legend.right;
    template.legend.top = 10;
    template.radar.center = ['50%', '60%'];
  } else if (widget.showLegendLocation === 'down') {
    delete template.legend.right;
    template.legend.bottom = 10;
    template.radar.center = ['50%', '40%'];
  }

  return template;
}
